package com.dcbeida.activity.zyff;

import android.app.Dialog;
import android.content.Intent;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.MessageQueue;
import android.support.annotation.Nullable;
import android.support.annotation.RequiresApi;
import android.support.v4.widget.NestedScrollView;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.sdk.android.oss.common.utils.BinaryUtil;
import com.dcbeida.R;
import com.dcbeida.activity.BaseActivity;
import com.dcbeida.activity.CaptureActivity;
import com.dcbeida.activity.CommonListActivity;
import com.dcbeida.activity.addnewpatient.AddNewPatientAct;
import com.dcbeida.activity.hospital.HospitalActivity;
import com.dcbeida.activity.sales.StoresalesContract;
import com.dcbeida.activity.sign.SignQrCodeActivity;
import com.dcbeida.bean.CardEnum;
import com.dcbeida.bean.CouponDrug;
import com.dcbeida.bean.CpreSendDrug;
import com.dcbeida.bean.DrugCode2Info;
import com.dcbeida.bean.DrugCodeInfo;
import com.dcbeida.bean.DrugCodeItem;
import com.dcbeida.bean.HospitalBean;
import com.dcbeida.bean.MyClientBean;
import com.dcbeida.bean.Patient;
import com.dcbeida.bean.SignStatusEnum;
import com.dcbeida.listern.DialogListener;
import com.dcbeida.utils.Constants;
import com.dcbeida.utils.DialogUtils;
import com.dcbeida.widget.TipDialog;
import com.dcbeida.widget.scanitem.DrugScanView;
import com.dcbeida.widget.scanitem.ScanView;
import com.dcbeida.widget.scanitem.YgDrugScanView;

import java.io.Serializable;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.Bind;
import butterknife.OnClick;

/**
 * 已购药品
 */
public class AlreadyDrugGiveActivity extends BaseActivity implements AlreadyDrugGiveContract.View {


    @Bind(R.id.img_back)
    ImageView img_back;

    @Bind(R.id.et_name)
    EditText et_name;

    @Bind(R.id.et_tel)
    EditText et_tel;

    @Bind(R.id.et_idcard)
    EditText et_idcard;

    @Bind(R.id.ll_yymc)
    LinearLayout ll_yymc;

    @Bind(R.id.tv_yymc)
    TextView tv_yymc;

    @Bind(R.id.et_jzys)
    EditText et_jzys;

    @Bind(R.id.add_Group)
    LinearLayout add_Group;

    @Bind(R.id.tv_empty_memo)
    TextView tv_empty_memo;

    @Bind(R.id.lin_jzys)
    LinearLayout lin_jzys;

    @Bind(R.id.ns_view)
    NestedScrollView ns_view;

    @Bind(R.id.tv_end_confim)
    TextView tv_end_confim;
    @Bind(R.id.tv_he)
    TextView tv_he;

    @Bind(R.id.yg_list)
    YgDrugScanView yg_list;

    @Bind(R.id.lin_add_drugs)
    LinearLayout lin_add_drugs;
    @Bind(R.id.tv_scan_detail)
    TextView tv_scan_detail;
    @Bind(R.id.ds_list)
    DrugScanView ds_list;
    int all = 0;

    @Bind(R.id.ll_tel_type)
    LinearLayout ll_tel_type;
    @Bind(R.id.tv_tel_type)
    TextView tv_tel_type;
    @Bind(R.id.ll_credit_type)
    LinearLayout ll_credit_type;
    @Bind(R.id.tv_crdeit_type)
    TextView tv_crdeit_type;
    @Bind(R.id.tv_sign_status)
    TextView tv_sign_status;


    @Bind(R.id.lin_already_scan)
    LinearLayout lin_already_scan;
    private AlreadyDrugGiveContract.Present mPresent;

    private boolean isConfirm = false;
    private int telType = 0;
    private int creditType=0;//默认0


    private DrugCodeInfo drugCodeInfo;
    private StringBuffer stringBuffer;

    private HospitalBean hospitalBean;

    private int patientid;
    private int signstatus;

    @Override
    protected int getLayoutResId() {
        return R.layout.activity_already_drug_give;
    }

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        initparam();
    }

    private void initparam() {
        mPresent = new AlreadyDrugGivePresenter(this, this);

    }

    @Override
    public void setData() {
        super.setData();
        tv_empty_memo.post(new Runnable() {
            @Override
            public void run() {
                int height = ns_view.getBottom() - add_Group.getTop();
                LinearLayout.LayoutParams layoutParams = (LinearLayout.LayoutParams) tv_empty_memo.getLayoutParams();
                layoutParams.height = height;
                tv_empty_memo.setLayoutParams(layoutParams);
            }
        });

        yg_list.setListener(new ScanView.EmptyListener() {
            @Override
            public void emptyCallBack() {
                tv_empty_memo.setText(getString(R.string.qjxygyp));
                add_Group.setVisibility(View.VISIBLE);
            }
        });

        ds_list.setListener(new ScanView.EmptyListener() {
            @Override
            public void emptyCallBack() {
                tv_empty_memo.setText(getString(R.string.qjxzy));
                add_Group.setVisibility(View.VISIBLE);
            }
        });

    }

    @OnClick({R.id.img_back, R.id.lin_already_scan, R.id.tv_end_confim, R.id.ll_yymc,R.id.ll_tel_type,R.id.ll_credit_type})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.img_back:
                finish();
                break;
            case R.id.lin_already_scan://
                Bundle b = new Bundle();
                b.putInt("type", CaptureActivity.TYPE_RE);
                b.putString("title", getString(R.string.ygypsm));
                showActivityForResult(CaptureActivity.class, b, Constants.RESULT_CAPTER);
                break;
            case R.id.tv_end_confim:

                if (TextUtils.isEmpty(et_name.getText().toString())) {
                    showTip("请填写患者姓名");
                    return;
                }
//                if (TextUtils.isEmpty(et_tel.getText().toString()) || et_tel.getText().toString().trim().length() != 11) {
//                    showTip("请正确填写患者手机号");
//                    return;
//                }
                if (telType == 0 && et_tel.getText().toString().length() !=11) {
                    showTip("请正确填写患者手机号码");
                    return;
                }

                if (telType == 1 && !et_tel.getText().toString().contains("-")) {
                    showTip("请正确填写患者固定电话");
                    return;
                }

                if (TextUtils.isEmpty(et_idcard.getText().toString())) {
                    showTip("请填写患者证件号");
                    return;
                }
                if (TextUtils.isEmpty(et_jzys.getText().toString())) {
                    showTip("请填写就诊医生");
                    return;
                }
                if (TextUtils.isEmpty(tv_yymc.getText().toString()) || "请选择".equalsIgnoreCase(tv_yymc.getText().toString())
                        || mPresent.getHospitalid() == 0) {
                    showTip("请选择医院");
                    return;
                }


                drugCodeInfo = new DrugCodeInfo();
                drugCodeInfo.setDoctorname(et_jzys.getText().toString());
                drugCodeInfo.setHospitalid(mPresent.getHospitalid());
                drugCodeInfo.setIdcardnum(et_idcard.getText().toString());
                drugCodeInfo.setPhonenum(et_tel.getText().toString());
                drugCodeInfo.setTruename(et_name.getText().toString());
                drugCodeInfo.setPatientid(patientid);
                drugCodeInfo.setSignstatus(signstatus);
                Map<String, List<DrugCodeInfo.DrugDTO>> infos = yg_list.getDatas();
                if (infos.isEmpty()) {
                    showTip("请扫码已购药品");
                    return;
                }
                stringBuffer = new StringBuffer();
                Set<Map.Entry<String, List<DrugCodeInfo.DrugDTO>>> entries = infos.entrySet();
                for (Map.Entry<String, List<DrugCodeInfo.DrugDTO>> entry : entries) {
                    List<DrugCodeInfo.DrugDTO> value = entry.getValue();
                    for (DrugCodeInfo.DrugDTO drugDTO : value) {
                        stringBuffer.append(drugDTO.getDrugcode()).append(",");
                    }
                }
                stringBuffer.deleteCharAt(stringBuffer.length() - 1);

                if (isConfirm) {
                    int count = 0;
                    Map<String, List<DrugCodeItem>> datas = ds_list.getDatas();
                    final StringBuffer s2 = new StringBuffer();
                    if (datas.isEmpty()) {
                    } else {
                        Set<Map.Entry<String, List<DrugCodeItem>>> entr = datas.entrySet();
                        for (Map.Entry<String, List<DrugCodeItem>> entry : entr) {
                            List<DrugCodeItem> value = entry.getValue();
                            for (DrugCodeItem drugDTO : value) {
                                count++;
                                s2.append(drugDTO.getDrugcode()).append(",");
                            }
                        }
                        s2.deleteCharAt(s2.length() - 1);
                    }


                    if (all == count) {
                        mPresent.addbuydrugpresent(drugCodeInfo, s2.toString(), stringBuffer.toString());
                    } else {
                        DialogUtils.showCountDialogTip(this, all, count, new DialogListener() {
                            @Override
                            public void onCancl(Dialog dialog) {
                                dialog.cancel();
                            }

                            @Override
                            public void onConfirm(Dialog dialog) {
                                dialog.cancel();
                                mPresent.addbuydrugpresent(drugCodeInfo, s2.toString(), stringBuffer.toString());
                            }
                        });
                    }
                    return;
                }


                if(patientid == 0){
                    mPresent.getPatientInfo(2,et_idcard.getText().toString());
                }else if(drugCodeInfo.getSignstatus() == SignStatusEnum.YQ.getType()){
                    mPresent.calcpresenddruglist(drugCodeInfo, stringBuffer.toString());
                }else {
                    b = new Bundle();
                    b.putInt("patientId",drugCodeInfo.getPatientid());
                    b.putInt("type",2);
                    showActivityForResult(SignQrCodeActivity.class, b, Constants.SIGN_NEXT);
                }



                break;
            case R.id.ll_yymc:
                b = new Bundle();
                showActivityForResult(HospitalActivity.class, b, Constants.HOSPITAL_TYPE);
                break;
            case R.id.ll_tel_type:
                b = new Bundle();
                b.putInt("type", 1);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_TEL_TYPE);
                break;
            case R.id.ll_credit_type:
                b = new Bundle();
                b.putInt("type", 0);
                showActivityForResult(CommonListActivity.class, b, Constants.RESULT_CRIDET_TYPE);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.i(AlreadyDrugGiveActivity.class.getName(), "#########requestCode:" + requestCode + ";######resultCode:" + resultCode);
        if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CAPTER) {
            String code = data.getStringExtra("code");
            Log.i(TAG, "---" + code);
            if (TextUtils.isEmpty(code)) {
                showTip("扫码返回的数据不正确,请重新扫码");
                return;
            }

            if (!isConfirm) {
                if (yg_list.isContains(code)) {
                    showTip("你扫入的监管码已重复，请检查");
                    return;
                }
                mPresent.queryCodeToDrugWithInfo(code);
            } else {
                if (ds_list.isContains(code)) {
                    showTip("你扫入的监管码已重复，请检查");
                } else
                    mPresent.querydruginfo(code);
            }


        } else if (requestCode == Constants.HOSPITAL_TYPE && resultCode == RESULT_OK) {//选择医院
            Bundle bundle = data.getExtras();
            if (null != bundle) {
                if (bundle.containsKey("hospitalBean")) {
                    hospitalBean = (HospitalBean) bundle.getSerializable("hospitalBean");
                    tv_yymc.setText(hospitalBean.getHospitalname());
                    mPresent.setHospitalid(hospitalBean.getHospitalid());
                }
            }

        }else if(resultCode == RESULT_OK && requestCode == Constants.RESULT_TEL_TYPE){
            String key = data.getStringExtra("key");
            tv_tel_type.setText(key);
            telType = data.getIntExtra("value",0);
        } else if (resultCode == RESULT_OK && requestCode == Constants.RESULT_CRIDET_TYPE){
            String key = data.getStringExtra("key");
            tv_crdeit_type.setText(key);
            creditType = data.getIntExtra("value",0);
        }else  if(resultCode == RESULT_OK && requestCode == Constants.SIGN_NEXT){
            int signStatus = data.getIntExtra("status",0);
            SignStatusEnum anEnum = SignStatusEnum.getEnum(signStatus);
            tv_sign_status.setText(anEnum.getName());
            tv_sign_status.setTextColor(getResources().getColor(anEnum.getColor()));
            if(SignStatusEnum.YQ.getType() ==signStatus) {
                mPresent.calcpresenddruglist(drugCodeInfo, stringBuffer.toString());
            }
        }else  if( resultCode == RESULT_OK && requestCode == Constants.REQUEST_ADD_PATIENT ){
            int patientId = data.getIntExtra("patientId", 0);
            mPresent.getPatientInfo(4, patientId+"");
        }

    }

    @Override
    public void showTip(String msg) {
        super.showTip(msg);
    }

    @Override
    public void showError(String message) {
        TipDialog tipDialog = new TipDialog(mContext).setMessage(message);
        tipDialog.show();
    }

    @Override
    public void showData(DrugCodeInfo info) {
        if (!TextUtils.isEmpty(info.getTruename())) {
            et_name.setText(info.getTruename());
        }

        if (!TextUtils.isEmpty(info.getPhonenum())) {
            et_tel.setText(info.getPhonenum());
        }

        if (!TextUtils.isEmpty(info.getDoctorname())) {
            et_jzys.setText(info.getDoctorname());
        }

        if (!TextUtils.isEmpty(info.getIdcardnum())) {
            et_idcard.setText(info.getIdcardnum());
        }

        if (!TextUtils.isEmpty(info.getHospitalname()) && mPresent.getHospitalid() != 0) {
            tv_yymc.setText(info.getHospitalname());

        }
        patientid = info.getPatientid();
        signstatus = info.getSignstatus();
        SignStatusEnum anEnum = SignStatusEnum.getEnum(info.getSignstatus());
        tv_sign_status.setText(anEnum.getName());
        tv_sign_status.setTextColor(getResources().getColor(anEnum.getColor()));

        add_Group.setVisibility(View.GONE);
        yg_list.addData(info.getDrug());
        ns_view.fullScroll(NestedScrollView.FOCUS_DOWN);
    }

    @RequiresApi(api = Build.VERSION_CODES.M)
    @Override
    public void showListDrug(List<CpreSendDrug> list) {
        lin_add_drugs.setVisibility(View.VISIBLE);
        isConfirm = true;
        add_Group.setVisibility(View.VISIBLE);
        yg_list.closeOperate();
        tv_scan_detail.setText(getString(R.string.zysm));
        tv_empty_memo.setText(getString(R.string.qjxzy));
        tv_end_confim.setText(getString(R.string.qrtj));
        for (CpreSendDrug cpreSendDrug : list) {
            View itemView = LayoutInflater.from(mContext).inflate(R.layout.drug_span_item, null);
            TextView tv_name = (TextView) itemView.findViewById(R.id.tv_name);
            TextView tv_he = (TextView) itemView.findViewById(R.id.tv_he);
            tv_name.setText(cpreSendDrug.getName());
            tv_he.setText(cpreSendDrug.getQuantity() + "");
            all += cpreSendDrug.getQuantity();
            lin_add_drugs.addView(itemView);
        }
        tv_he.setText(all + "");
        Looper.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
            @Override
            public boolean queueIdle() {
                ns_view.fullScroll(NestedScrollView.FOCUS_DOWN);
                return false;
            }
        });
    }


    @Override
    public void showAddDrug(DrugCode2Info info) {
        add_Group.setVisibility(View.GONE);
        ds_list.addData(info.getDrug());
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            Looper.getMainLooper().getQueue().addIdleHandler(new MessageQueue.IdleHandler() {
                @Override
                public boolean queueIdle() {
                    ns_view.fullScroll(NestedScrollView.FOCUS_DOWN);
                    return false;
                }
            });
        }


    }


    @Override
    public void showSuccess() {
        showTip("援助发放成功");
        finish();
    }

    @Override
    public void getPatientInfo(Patient patient) {
        if(patient.getId() > 0){
            showPatient(patient);
            patientid = patient.getId();
            signstatus = patient.getSignstatus();
            drugCodeInfo.setHospitalid(patient.getHospitalid());
            drugCodeInfo.setIdcardnum(patient.getIdcardnum());
            drugCodeInfo.setPhonenum(patient.getPhonenum());
            drugCodeInfo.setTruename(patient.getTruename());
            drugCodeInfo.setPatientid(patientid);
            drugCodeInfo.setSignstatus(signstatus);
            if(drugCodeInfo.getSignstatus() == SignStatusEnum.YQ.getType()){
                mPresent.calcpresenddruglist(drugCodeInfo, stringBuffer.toString());
            }else {
                Bundle b = new Bundle();
                b.putInt("patientId",drugCodeInfo.getPatientid());
                b.putInt("type",2);
                showActivityForResult(SignQrCodeActivity.class, b, Constants.SIGN_NEXT);
            }
        }else{
            addPatient();
        }
    }

    public void showPatient(Patient patient) {
        et_tel.setText(patient.getPhonenum());
        et_idcard.setText(patient.getIdcardnum());
        et_name.setText(patient.getTruename());
        tv_yymc.setText(patient.getHospitalname());
        String cardName = CardEnum.getCardName(patient.getCardtype());
        tv_crdeit_type.setText(cardName);
        creditType = patient.getCardtype();
        if(patient.getPhonenum() != null && patient.getPhonenum().contains("-")){
            telType =1;
            tv_tel_type.setText("固定电话");
        }else{
            tv_tel_type.setText("手机号");
        }
        SignStatusEnum anEnum = SignStatusEnum.getEnum(patient.getSignstatus());
        tv_sign_status.setText(anEnum.getName());
        tv_sign_status.setTextColor(getResources().getColor(anEnum.getColor()));
    }

    @Override
    public void addPatient() {
        //根据患者姓名未查到患者，显示添加弹窗
        DialogUtils.showDialogAddNewPatient(AlreadyDrugGiveActivity.this, R.string.wzdghz, new DialogListener() {
            @Override
            public void onCancl(Dialog dialog) {
                dialog.dismiss();
            }

            @Override
            public void onConfirm(Dialog dialog) {
                dialog.dismiss();
                Bundle bundle = new Bundle();
                MyClientBean myClientBean = new MyClientBean();
                myClientBean.setTruename(et_name.getText().toString().trim());
                myClientBean.setPhonenum(et_tel.getText().toString().trim());
                myClientBean.setCardtype(creditType);
                myClientBean.setIdcardnum(et_idcard.getText().toString().trim());
                if( hospitalBean != null) {
                    myClientBean.setHospitalid(hospitalBean.getHospitalid());
                    myClientBean.setHospitalname(hospitalBean.getHospitalname());
                }
                myClientBean.setDoctorname(et_jzys.getText().toString().trim());
                bundle.putSerializable("myClientBean", myClientBean);
                bundle.putInt("operaterType",0);
                showActivityForResult(AddNewPatientAct.class, bundle, Constants.REQUEST_ADD_PATIENT);

            }
        }, R.string.cancel, R.string.xzhz);
    }

    @Override
    public void setPresenter(AlreadyDrugGiveContract.Present presenter) {

    }
}
